<template>
  <div>
    <el-dialog title="产品编辑" :visible.sync="dialogShow" @close="handleCancel" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="title">
          <el-input placeholder="请输入名称" v-model="form.title" :disabled="isDisabled" clearable></el-input>
        </el-form-item>

        <el-form-item label="商品图">
          <upload :fileList="fileList" :limit="2" ref="uploadImages"></upload>
        </el-form-item>

         <el-form-item label="单位">
          <el-select v-model="form.unit" filterable placeholder="请选择" :disabled="isDisabled">
            <el-option
              v-for="item in unit_list"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="商品分类" prop="category">
          <el-select v-model="form.category" filterable placeholder="请选择" :disabled="isDisabled">
            <el-option-group
              v-for="group in productData.category"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <tags ref="tags"></tags>
        </el-form-item>
        

        <el-row :span="15">
          <div class="library_sku">
            <h3>产品库</h3>
            <el-row :gutter="16">
              <el-table
                style="margin-left:10px"
                ref="libraySku"
                border
                stripe
                :data="productData.library_sku"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="sku_str" label="属性"></el-table-column>
                <el-table-column prop="price" label="价格">
                  <template slot-scope="scope">
                    <el-input
                      placeholder="请输入价格"
                      type="number"
                      min="0.00"
                      step="0.01"
                      v-model="scope.row.price"
                      clearable
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="suggest" label="参考价格"></el-table-column>
                <el-table-column prop="bestprice" label="优惠价格">
                  <template slot-scope="scope">
                    <el-input
                      placeholder="请输入价格"
                      type="number"
                      min="0.00"
                      step="0.01"
                      v-model="scope.row.best_price"
                      clearable
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="bestprice" label="是否开启优惠">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.open_best"
                      :active-text="scope.row.open_best == 1 ? '打开':'关闭'"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    ></el-switch>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </div>
        </el-row>

        <el-row style="margin-top:20px;">
          <div class="my_sku">
            <h3>我添加的属性</h3>
            <el-popover
              placement="right"
              width="200"
              @hide="addSku = {value: '',price: ''}"
              v-model="addSkuVis"
            >
              <el-form :inline="true" :model="addSku" class="demo-form-inline">
                <el-form-item label="属性">
                  <el-input v-model="addSku.value" placeholder="属性" clearable></el-input>
                </el-form-item>
                <el-form-item label="价格">
                  <el-input
                    v-model="addSku.price"
                    placeholder="价格"
                    type="number"
                    min="0.00"
                    step="0.01"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onAddSku">添加</el-button>
                </el-form-item>
              </el-form>
              <el-button
                style="margin:10px 0"
                type="default"
                slot="reference"
                icon="el-icon-edit"
              >添加属性</el-button>
            </el-popover>
            <el-row :gutter="20">
              <el-table
                style="margin-left:10px"
                ref="mySku"
                border
                stripe
                :data="productData.my_sku"
              >
                <el-table-column prop="sku_str" label="属性"></el-table-column>
                <el-table-column prop="price" label="价格">
                  <template slot-scope="scope">
                    <el-input
                      placeholder="请输入价格"
                      type="number"
                      min="0.00"
                      step="0.01"
                      v-model="scope.row.price"
                      clearable
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="bestprice" label="优惠价格">
                  <template slot-scope="scope">
                    <el-input
                      placeholder="请输入价格"
                      type="number"
                      min="0.00"
                      step="0.01"
                      v-model="scope.row.best_price"
                      clearable
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="bestprice" label="是否开启优惠">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.open_best"
                      :active-text="scope.row.open_best == 1 ? '打开':'关闭'"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="删除">
                  <template slot-scope="scope">
                    <el-button type="danger" @click="handleDelSku(scope)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </div>
        </el-row>

        <el-row style="margin-top:20px;">
          <editor-bar v-model="form.description" ref="editor" :isClear="isClear"></editor-bar>
        </el-row>

        <el-form-item style="margin-top:15px;">
          <el-button type="primary" @click="onSubmit">更新</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>

      <el-dialog ref="preview" :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { successMsg, errorMsg } from "@/util/message"
import { isNull } from "@/util/util";
import EditorBar from '@/views/merchant/common/editorBar'
import upload from '@/views/merchant/common/upload'
import request from '@/router/axios'
import { baseUrl } from '@/config/env'
import tags from './tags'



export default {
  props: ['id', 'showDetail'],
  created() {
    // this.handleShow(this.id)
  },
  computed: {
    isDisabled() {  //当为产品库时，disable
      if (!isNull(this.productData))      {
        return this.productData.product.is_library
      }
      return false
    },
    getImages() {
      let urls = this.fileList.map(item => {
        return item.url
      })
      return urls.join(',')
    }
  },
  components: {
    upload, EditorBar,tags
  },
  data() {
    return {
      form: {
        cover: '',
        title: '',
        category: '',
        description: '',
        unit:'',
      },
      dialogShow: false,
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 60, message: '长度在 3 到 60 个字符', trigger: 'blur' }
        ],
      },
      productData: {},
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],  //上传文件
      librarySelection: [],
      submitProduct: {
        "product": {},
        "library_sku": [],
        "my_sku": []
      },
      addSku: {
        value: '',
        price: ''
      },
      addSkuVis: false,  //控制是否显示
      isClear: true,
      overPricePercent: 0,
      unit_list:[]
    }
  },
  methods: {
    onSubmit() {
      // 产品赋值
      this.submitProduct.product = {
        title: this.form.title,
        image: this.getImages,
        category_id: this.form.category,
        description: this.$refs.editor.info_,
        tags: this.$refs.tags.dynamicTags,
        unit: this.form.unit
      }

      this.submitProduct.library_sku = []
      this.submitProduct.my_sku = []

      if (!isNull(this.productData.library_sku))      {
        if (this.librarySelection.length == 0)        {

          return errorMsg(this, '至少选择一项')
        }
        console.log(this.librarySelection)

        this.submitProduct.library_sku = []

        let checkEmpty = false
        let overItem = ''
        let checkOver = false
        this.librarySelection.forEach(item => {
          if (this.checkOverPrice(item.price, item.suggest))
          {
            checkOver = true
            overItem = item
            return false
          }
          if (isNull(item.price))          {
            checkEmpty = true
          }

          this.submitProduct.library_sku.push({
            id: item.id,
            price: item.price,
            best_price: item.best_price,
            open_best: item.open_best
          })
        })

        if (checkOver)
        {
          return errorMsg(this, '属性' + overItem.sku_str + '的价格输入错误，不能超过参考价格的' + this.overPricePercent + '%')
        }

        // 查找是否为空
        if (checkEmpty)        {
          return errorMsg(this, '输入价格不能为空')
        }
      }


      this.submitProduct.my_sku = []
      this.submitProduct.my_sku = this.productData.my_sku

      let checkEmpty = false
      this.submitProduct.my_sku.forEach(item => {
        if (isNull(item.price))        {
          checkEmpty = true
        }
      })

      if (checkEmpty)      {
        return errorMsg(this, '输入价格不能为空')
      }

      this.handleUpdate()
    },
    checkOverPrice(val, suggest) {
      let overPricePerson = parseFloat(this.overPricePercent / 100)
      let overPrice = suggest * overPricePerson
      if (isNull(overPrice))
      {
        return false
      }

      if ((val < (parseFloat(suggest) - parseFloat(overPrice))) ||
        (val > ((parseFloat(suggest) + parseFloat(overPrice)))))
        return true
      return false
    },
    getOverPriceSetting() {
      request.get(baseUrl + '/settings/', {}).then(res => {
        if (res.data.status == 1)
        {
          let range = res.data.result.price_range
          this.overPricePercent = range
        }
      })
    },
    handleShow(id) {
      let vm = this
      let param = {
        id: id
      }
      
      this.submitProduct = {
        "product": {},
        "library_sku": [],
        "my_sku": []
      }

      this.tableLoading = true;
      this.dialogShow = this.showDetail

      //获取改价的价格
      this.getOverPriceSetting()

      this.$store
        .dispatch("GetProductShow", param)
        .then(
          res => {
            if (res.data.status == 1)            {
              vm.productData = res.data.result.data || []
              if (!isNull(vm.productData))              {
                vm.fillForm(vm.productData.product)

                this.$nextTick(function () {
                  // 在dom已经更新之后
                  vm.productData.library_sku.forEach((row) => {
                    if (row.check)                    {
                      this.$refs.libraySku.toggleRowSelection(row, true);
                    }
                  });

                   vm.unit_list = res.data.result.data.unit_list
                  this.$refs.tags.dynamicTags = vm.productData.product.tags
                })
              

              }
            }
            this.tableLoading = false;
          }, error => {
            this.tableLoading = false;
            errorMsg(this, error)
          })
    },
    fillForm(data) {
      let vm = this
      vm.form.title = data.title
      //vm.form.category = data.category_id
      vm.fileList = vm.filterImages(data)
      vm.form.description = data.description

      vm.$set(vm.form,'unit',data.unit)
      vm.$set(vm.form,'category',data.category_id)

      //vm.form.unit = data.unit
      //this.$refs.editor.updateTxt()  //更新数据
      //增加图片的现实
    },
    filterImages(data) {
      let images = data.cover.split(',')
      let fileList = []
      images.forEach(item => {
        if (!(item.indexOf("tmp.jpg") >= 0))
        {
          fileList.push({ url: item })
        }
      })

      return fileList
    },
    // 移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 缩略图预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleCancel() {
      this.productData = {}
      this.submitProduct = {
        "product": {},
        "library_sku": [],
        "my_sku": []
      }
      this.fileList = []
      this.form = {}
      this.dialogShow = false
      this.$refs.tags.dynamicTags = []
    },
    handleSelectionChange(val) {
      this.librarySelection = val;
    },
    handleUpdate()   //更新产品信息
    {
      let vm = this
      let param = Object.assign({
        id: this.id
      }, this.submitProduct)

      this.$store
        .dispatch("UpdateProduct", param)
        .then(
          res => {
            if (res.data.status == 1)            {
              successMsg(this, '更新成功')
              this.handleCancel()
              this.$emit('refresh', '')
            }
            else            {
              errorMsg(this, '更新错误')
            }
          }, error => {
            errorMsg(this, error)
          })
    },
    // 添加sku
    onAddSku() {
      if (isNull(this.addSku.value))      {
        return errorMsg(this, '属性不能为空')
      }
      if (isNull(this.addSku.price))      {
        return errorMsg(this, '价格不能为空')
      }

      // 增加属性
      let vm = this
      let param = Object.assign({
        id: this.id
      }, this.addSku)

      this.$store
        .dispatch("AddProductOwnSku", param)
        .then(
          res => {
            if (res.data.status == 1)            {
              successMsg(this, '添加成功')
              // 添加这个sku到底部
              let newSku = res.data.result.data
              newSku.best_price = 0
              newSku.open_best = false
              this.productData.my_sku.push(newSku)
              this.addSkuVis = false

            }
            else            {
              errorMsg(this, '添加失败')
            }
          }, error => {
            errorMsg(this, error)
          })
    },
    handleDelSku(scope) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$store
          .dispatch("DelProductSku", {
            id: scope.row.id
          })
          .then(
            res => {
              if (res.data.status == 1)              {
                successMsg(this, '删除成功')
                // 去除这条sku
                this.productData.my_sku.splice(scope.$index, 1)
              }
              else              {
                errorMsg(this, '删除失败')
              }
            }, error => {
              errorMsg(this, error)
            })
      }).catch((error) => {
        console.log(error)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    }
  }
}
</script>




